//
//  GestureRecognizerViewController.swift
//  iOS-RxSwift-Tutorials_Example
//
//  Created by mengru.tian on 2020/9/21.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift

class GestureRecognizerViewController: UIViewController {

    private let disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "26.UI控件扩展7：UIGestureRecognizer"
        view.backgroundColor = .white
        
        test()
//        test2()
        test3()
    }
    
    // 滑动手势
    func test() {
        
        //添加一个上滑手势
        let swipe = UISwipeGestureRecognizer()
        swipe.direction = .up
        self.view.addGestureRecognizer(swipe)
         
        //手势响应
        swipe.rx.event
            .subscribe(onNext: { [weak self] recognizer in
                //这个点是滑动的起点
                let point = recognizer.location(in: recognizer.view)
                self?.showAlert(title: "向上划动", message: "\(point.x) \(point.y)")
            })
            .disposed(by: disposeBag)
    }
    
    // 滑动手势2
    func test2() {
        //添加一个上滑手势
        let swipe = UISwipeGestureRecognizer()
        swipe.direction = .up
        self.view.addGestureRecognizer(swipe)
         
        //手势响应
        swipe.rx.event
            .bind { [weak self] recognizer in
                //这个点是滑动的起点
                let point = recognizer.location(in: recognizer.view)
                self?.showAlert(title: "向上划动", message: "\(point.x) \(point.y)")
            }
            .disposed(by: disposeBag)
    }
    
    //显示消息提示框
    func showAlert(title: String, message: String) {
        let alert = UIAlertController(title: title, message: message,
                                      preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .cancel))
        self.present(alert, animated: true)
    }
    
    // 实现点击页面任意位置，输入框便失去焦点
    func test3() {
        //添加一个点击手势
        let tapBackground = UITapGestureRecognizer()
        view.addGestureRecognizer(tapBackground)

        //页面上任意处点击，输入框便失去焦点
        tapBackground.rx.event
           .subscribe(onNext: { [weak self] _ in
               self?.view.endEditing(true)
           })
           .disposed(by: disposeBag)
    }

}
